<?php

namespace App\Models;

use App\Services\Event;
use Illuminate\Auth\Authenticatable;

class User extends  \Illuminate\Foundation\Auth\User
{
    use Authenticatable;
    protected $guarded = [];

    protected function casts()
    {
        return [
            "token_created_at" => 'datetime'
        ];
    }

    public function invitations()
    {
        return $this->hasMany(Invitation::class);
    }

    public function joinedEvents()
    {
        return $this->belongsToMany(Event::class, 'event_attendee', 'user_id', 'event_id');
    }

    public function hasInvitation($event)
    {
        return $this->invitations()->get()->contains(function($invitation) use ($event) {
            return $invitation->event_id == $event->id;
        });
    }

    public function joined($event)
    {
        return $this->joinedEvents()->get()->contains(function($evt) use ($event) {
            return $evt->id == $event->id;
        });
    }

    public function canJoin($event)
    {
        if($event->type==="PUBLIC"){
            return $event->participants->count() < $event->capacity
                && !$this->joined($event)
                && $event->start_at > now();
        }
        return $this->hasInvitation($event)
            && !$this->joined($event)
            && $event->participants->count() < $event->capacity
            && $event->start_at > now();
    }

    public function canInvite($event)
    {
        return $event->type==="PRIVATE"
            && $event->creator_id == $this->id;
    }

    public function canBeInvited($event)
    {

    }

    public function received_messages()
    {
        return $this->hasMany(Message::class, 'receiver_id');
    }

    public function sent_messages()
    {
        return $this->hasMany(Message::class, 'sender_id');
    }

}
